﻿using KhoaLuan.Areas.Admin.ActionFilters;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KhoaLuan.Areas.Admin.Controllers
{
     [Security]
    public class CustomersController : Controller
    {
        //
        // GET: /Admin/Customers/
        LuanVanEntities db = new LuanVanEntities();

        public ActionResult Index()
        {
            var model = new Customer();
            ViewBag.Customers = db.Customers;
            return View(model);
        }
        public ActionResult Insert (Customer model)
        {
            var f = Request.Files["UpPhoto"];
            if (!String.IsNullOrEmpty(f.FileName))
            {
                f.SaveAs(Server.MapPath("~/images/customers/" + f.FileName));
                model.Photo = f.FileName;
            }
            try
            {
                db.Customers.Add(model);
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                ViewBag.Customers = db.Customers;
              
                return View("Index", model);
            }
        }
        public ActionResult Update (Customer model)
        {
            var f = Request.Files["UpPhoto"];
            if(!String.IsNullOrEmpty(f.FileName))
            {
                f.SaveAs(Server.MapPath("~/images/customers/" + f.FileName));
                model.Photo = f.FileName;
            }
            try
            {
                db.Entry(model).State = EntityState.Modified;
                db.SaveChanges();
                ModelState.AddModelError("", "Cập nhật Thành Công");
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }
            ViewBag.Customers = db.Customers;
            return View("Index", model);
        }
        public ActionResult Delete (String Id)
        {
            var model = db.Customers.Find(Id);
            db.Customers.Remove(model);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        public ActionResult Edit(String Id)
        {
            var model = db.Customers.Find(Id);
            ViewBag.Customers = db.Customers;
            return View("Index", model);
        }
	}
}